package org.pi.common.vision

import org.pi.common.matrix.FloatMatrix
import org.pi.common.matrix.Api._
import org.pi.common.time.Api._

trait VisionApi extends org.pi.common.vision.tool.BlurToolTrait
with org.pi.common.vision.tool.GradientToolTrait
with org.pi.common.vision.tool.ConvolutionToolTrait
with org.pi.common.vision.tool.BinaryMorphologyToolTrait
with org.pi.common.vision.tool.MedianFilterToolTrait
{

	// =====================
	// imread + imwrite
	// =====================
	def imread(filename: String) = org.pi.common.vision.io.ImageIO.loadRgbArrayFromFile(filename)
	def imwrite(filename: String, array: FloatMatrix) {
	  	if (array.shape.length==2) org.pi.common.vision.io.ImageIO.saveGrayArray(filename, array, true, 0, 0)
	  	else if (array.shape.length==3) org.pi.common.vision.io.ImageIO.saveRgbArray(filename, array, true, 0, 0)
	  	else throw new Error("dont know how to imwrite a matrix with "+array.shape.length+" dimensions")
  	}
	def imwrite(filename: String, array: FloatMatrix, minval: Float, maxval: Float) {
		if (array.shape.length==2) org.pi.common.vision.io.ImageIO.saveGrayArray(filename, array, false, minval, maxval)
		else if (array.shape.length==3) org.pi.common.vision.io.ImageIO.saveRgbArray(filename, array, false, minval, maxval)
		else throw new Error("dont know how to imwrite a matrix with "+array.shape.length+" dimensions")
	}
	
	// =====================
	// colorspace stuff
	// =====================
	def hsv2rgb(hsv: FloatMatrix) : FloatMatrix = org.pi.common.vision.tool.ColorSpaceTool.hsv2rgb(hsv)
	def rgb2hsv(hsv: FloatMatrix) : FloatMatrix = org.pi.common.vision.tool.ColorSpaceTool.rgb2hsv(hsv)
	def rgb2gray(rgb: FloatMatrix) = org.pi.common.vision.io.ImageIO.makeGrayArrayFromImage( org.pi.common.vision.io.ImageIO.createBufferedImageFromRgbArray(rgb, false, 0, 1) );
}

object Api 
extends VisionApi 
{
	// =====================
	// test
	// =====================
	def main(arg: Array[String]): Unit = {
		println("MLab Demo")
		import org.pi.common.geom._

		val A = FloatMatrix(200,320)
		val l = Line( Point(70,70), Point(320-70,200-70) )
		printlnTicToc("draw Line") {
			for (y <- 0 until 200) for (x <- 0 until 320) A(y,x) = l distance Point(x,y)
		}
		imwrite("linedistance.png",A)

		val R = rand(200,320,3)
		for (y <- 0 until 200) for (x <- 0 until 320) R(y,x,2) = l distance Point(x,y)
		imwrite("randRgb.png",R)
		imwrite("randHsv.png",hsv2rgb(R))

		println("end MLab demo")
	}
}
